#!/bin/bash

mydir=$PWD

# get xxx from dirname 'app-xxx'
appname=$(basename $mydir |sed -e 's/^app-//')
fs_param=""
net_param=""
cmd_param=""
app_param=""
kraft='/home/wanghui/Projects/kraftkit/dist/kraft'

# e,g.
#  kraft='/home/wanghui/Projects/kraftkit/dist/kraft'
#  libs=(musl lwip iperf3)
#  net=true
#  fs=true
#  app_param="-s"
if [ ! -f build.config ]; then
    echo -e "kraft=\"/usr/bin/kraft\"\nlibs=()\nnet=false\nfs=false\napp_param=\"\"" > build.config
fi

. build.config

s=
for x in ${libs[@]};do 
  if [ -z "$s" ];then
    s="${mydir}/.unikraft/libs/$x"
  else
    s="${s}:${mydir}/.unikraft/libs/$x"
  fi
done

if $net; then
    net_param="--bridge-netdev virbr0"
    cmd_param="netdev.ipv4_addr=172.44.0.2 netdev.ipv4_gw_addr=172.44.0.1 netdev.ipv4_subnet_mask=255.255.255.0 -- ${app_param}"
else
    cmd_param=" -- ${app_param}"
fi

if $fs; then
    fs_param="--local-fsdev ${mydir}/fs0"
fi

if [ "$1" == "make" ]; then
  LANG=C make \
  N=app-$appname \
  C=${mydir}/.config.app-${appname}_kvm-x86_64 \
  O=${mydir}/build \
  A=${mydir} \
  L=$s \
  -C ${mydir}/.unikraft/unikraft \
  --no-print-directory || exit 1
elif [ "$1" == "config" ]; then
  make \
  N=app-${appname} \
  C=${mydir}/.config.app-${appname}_kvm-x86_64 \
  O=${mydir}/build \
  A=${mydir} \
  L=$s \
  menuconfig \
  -C ${mydir}/.unikraft/unikraft \
  --no-print-directory || exit 1
  exit 0
elif [ "$1" == "clean" ]; then
  $kraft clean
  exit 0
elif [ "$1" == "properclean" ]; then
  $kraft properclean
  exit 0
elif [ "$1" == "build" ]; then
  LANG=C $kraft build
elif [ "$1" == "run" ]; then
  ip a s virbr0 &>/dev/null || { brctl addbr virbr0; ip addr add  172.44.0.1/24 dev virbr0; ip link set dev virbr0 up; }

  $kraft run --log-level debug \
  -M 1024 \
  --no-monitor \
  $net_param \
  $fs_param \
  -- \
  $cmd_param \
  | tee /tmp/a.log 2>&1
else
  echo -e "Usage:"
  echo -e "    $0 config"
  echo -e "    $0 make"
  echo -e "    $0 build       (kraft build)"
  echo -e "    $0 clean       (kraft clean)"
  echo -e "    $0 properclean (kraft properclean)"
  echo -e "    $0 run         (kraft run)"
  exit 0
fi

